const Service = require('egg').Service;

class HomeService extends Service {
	async housing() {
		const {
			ctx,
			app
		} = this;
		// 分页 模糊查询 
		const {
			pageIndex,
			pageSize,
			keyword,
			pid
		} = ctx.query;
		let provinces = []
		let sql = `select * from housing where 1=1 `
		let sqlCount = `select count(id) as total from housing where 1=1 `
		if (keyword) {
			sql += `and title like "%${keyword}%" `
			sqlCount += `and title like "%${keyword}%" `
		}
		if (pageIndex && pageSize) {
			sql += `limit ${(pageIndex-1)*pageSize},${pageSize}`
		}
		if (pid) {
			let proSql = `select * from city where pid=${pid}`
			provinces = await app.mysql.query(proSql)
		}
		const data = await app.mysql.query(sql)
		const [{
			total
		}] = await app.mysql.query(sqlCount)
		return {
			data,
			provinces,
			total
		}
	}
	async delHousing() {
		const {
			ctx,
			app
		} = this;
		const data = await app.mysql.delete('housing', {
			id: ctx.params.id
		}); // 根据id删除
		return data
	}
	async addHousing() {
		const {
			ctx,
			app
		} = this;
		const data = await app.mysql.insert('housing', {
			...ctx.request.body,
			create_time: Date.now()
		})
		return data;
	}
	async editHousing() {
		const {
			ctx,
			app
		} = this;
		const data = await app.mysql.update('housing', {
			...ctx.request.body,
		})
		return data;
	}
	async editType() {
		const {
			ctx,
			app
		} = this
		const data = await app.mysql.update('housing', {
			...ctx.request.body,
		})
		return data;
	}
}

module.exports = HomeService;